package com.skytech.tax.customsdatawarehouse.singlewindow.revokelist.domain.dao;

import com.skytech.tax.customsdatawarehouse.singlewindow.revokelist.domain.entity.CusAutoRevokeList;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/11/9
 */
@Repository
public class CusAutoRevokeListDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String selectRevokeListSql = "SELECT decModSeqNo, revokeList, entryId, cusCiqNo, updateTime, storageTime FROM sw_cus_auto_revoke_list WHERE 1=1";

    public CusAutoRevokeList findByDecModSeqNo(String decModSeqNo) {
        StringBuilder sql = new StringBuilder(this.selectRevokeListSql);
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotEmpty(decModSeqNo)) {
            sql.append(" AND decModSeqNo = ? ");
            params.add(decModSeqNo);
        }
        try {
            return namedParameterJdbcTemplate.getJdbcOperations()
                    .queryForObject(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(CusAutoRevokeList.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private String deleteRevokeListSql = "DELETE FROM sw_cus_auto_revoke_list WHERE decModSeqNo = ?";

    public void delete(String decModSeqNo) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteRevokeListSql, decModSeqNo);
    }

    private final String saveRevokeListSql = "INSERT INTO sw_cus_auto_revoke_list " +
            "(decModSeqNo, revokeList, entryId, cusCiqNo, updateTime, socialCreditCode, storageTime) VALUES (:decModSeqNo, :revokeList, :entryId, :cusCiqNo, :updateTime, :socialCreditCode, :storageTime)";

    public void save(CusAutoRevokeList list) {
        list.setStorageTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        this.namedParameterJdbcTemplate.update(this.saveRevokeListSql, new BeanPropertySqlParameterSource(list));
    }
}
